package com.attilax.zip;

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.util.Collection;  
import java.util.HashMap;  
import java.util.Iterator;  
  
import DocHandler.DocTypeNameParse;  
import DocHandler.IDocHandler;  
  
import com.mucommander.file.AbstractFile;  
import com.mucommander.file.FileFactory;  
import com.mucommander.file.impl.rar.provider.RarFile;  
import com.mucommander.file.impl.rar.provider.de.innosystec.unrar.rarfile.FileHeader;  
/** 
* IDocHandler 为自己写的接口类 
* 
*/  
public class RarExtractor implements IDocHandler {  
    // 每次读取的字节大小  
    private int BLOCKSIZE = 1024;  
    // 临时文件编号  
    private int FILE_COUNT = 0;  
  
    public int getText(InputStream inputStream, StringBuffer strBuff) {  
String fileDir = "f://wang" + FILE_COUNT;  
FILE_COUNT++;  
String fileName = null;  
try { // 将文件写入磁盘上  
     writeTodev(inputStream, fileDir);  
     // 从磁盘上读取文件  
     File file = new File(fileDir);  
     String[] subFilePath = file.list();  
     fileName = fileDir + "//" + subFilePath[0];  
     AbstractFile abstractFile = FileFactory.getFile(fileName);  
     RarFile rarFile = new RarFile(abstractFile);  
     Collection collection = rarFile.getEntries();  
     IDocHandler docHandler = null;  
     for (Iterator iterator = collection.iterator(); iterator.hasNext();) {  
   FileHeader fileHeader = (FileHeader) iterator.next();  
   String subFileName = fileHeader.getFileNameString();  
   // 输出rar文档里的文档名  
   System.out.println("subFileName:" + subFileName);  
  
   InputStream subinputStream = rarFile.getEntryInputStream(subFileName);  
   /** 
   * DocTypeNameParse为文自己写的文档类型判断类。 
   */  
   String fileType = DocTypeNameParse.getTypeName(subFileName);  
   // 输出文档的类型  
   System.out.println("fileType:" + fileType);  
  
   docHandler = (IDocHandler) this.ExctractMap.get(fileType);  
   docHandler.getText(subinputStream, strBuff);  
   subinputStream.close();//这里必须关闭流，否则在遇到有文档异常时，流就会卡主  
     }  
     // System.out.println("strBuff:" + strBuff);  
} catch (IOException e) {  
     e.printStackTrace();  
}  
// 删除临时文件  
deleteFile(fileDir);  
return 0;  
    }  
  
    // 将文件写入磁盘上  
    private void writeTodev(InputStream inputStream, String fileDir) {  
byte[] b = new byte[BLOCKSIZE];  
int readCount = 0;  
try {  
     File file = new File(fileDir);  
     if (!file.exists())  
   file.mkdirs();  
     File subFile = new File(fileDir, "tempfile.rar");  
     FileOutputStream os = new FileOutputStream(subFile);  
     while ((readCount = inputStream.read(b)) > 0) {  
   os.write(b, 0, readCount);  
     }  
     os.close();  
} catch (IOException e) {  
     e.printStackTrace();  
}  
    }  
  
    // 删除临时文件  
    private void deleteFile(String fileName) {  
File file = new File(fileName);  
File[] subFile = file.listFiles();  
for (int i = 0; i < subFile.length; i++) {  
     subFile[i].delete();  
}  
file.delete();  
    }  
}  